﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using blackhouse.BlackApart.Business.Reservations;
using blackhouse.BlackApart.Business.Apartments;
using System.Web.UI.WebControls;
using blackhouse.BlackApart.Web;
using System.Configuration;
using blackhouse.BlackApart.Business;
using System.Text;
using blackhouse.BlackApart.Business.ApartmentServices;
using System.Web.UI;
using blackhouse.BlackApart.Business.Prices;

namespace blackhouse.Aparts.Web {
    public static class ApartsHelper {

        //public static string PrintPrice(this IUserApartmentsReservation reservation) {
        //    return new Currencies.Currency(reservation.TotalPrice, "PLN", 2).ToCurrency(reservation.Client.PrefferCurrency).ToString();
        //}

        //public static string PrintPricePerNight(this IUserApartmentsReservation reservation) {
        //    int lengthOfStay = (int)Math.Ceiling((reservation.DepartureDate - reservation.ArrivalDate).TotalDays);
        //    return new Currencies.Currency(reservation.TotalPrice / lengthOfStay, "PLN", 2).ToCurrency(reservation.Client.PrefferCurrency).ToString();
        //}

        public static string FormatLengthOfStay(DateTime arrivalDate, DateTime departureDate) {
            int lengthOfStay = (int)Math.Ceiling((departureDate - arrivalDate).TotalDays);
            return FormatLengthOfStay(lengthOfStay);
        }

        public static string FormatLengthOfStay(int lengthOfStay) {
            if (lengthOfStay == 1)
                return "1 dzień";
            else
                return lengthOfStay + " dni";
        }

        //public static double GetPricePerNight(double price, IUserApartmentsReservation reservation) {
        //    return price / (reservation.DepartureDate.Date - reservation.ArrivalDate.Date).TotalDays;
        //}

        public static void PopulateSelectedApartments(List<IReservation> reservationItems, Repeater repeater) {
            Dictionary<IApartment, int> d = new Dictionary<IApartment, int>();
            foreach (IReservation r in reservationItems) {
                if (!d.ContainsKey(r.Apartment))
                    d.Add(r.Apartment, 0);
                d[r.Apartment]++;
            }

            List<string> s = new List<string>();
            foreach (KeyValuePair<IApartment, int> kvp in d) {
                string si = kvp.Value + " apartment";
                if (kvp.Value > 1) si += "y";
                si += " " + kvp.Key.Group.Name + " (" + kvp.Key.NumberOfPeople + " osobowy)";
                s.Add(si);
            }
            repeater.DataSource = s;
            repeater.DataBind();
        }

        public static void PopulateSelectedApartmentsWithLink(IWebReservation reservation, Repeater repeater) {
            Factory factory = Factory.Instance();
            Dictionary<IApartmentGroup, int> d = new Dictionary<IApartmentGroup, int>();
            foreach (ApartmentWebReservation r in reservation.ApartmentReservation) {
                IApartmentGroup group = factory.GetApartment(r.ApartmentId).Group;
                if (!d.ContainsKey(group))
                    d.Add(group, 0);
                d[group]++;
            }

            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<IApartmentGroup, int> kvp in d) {
                string si = kvp.Value + " apartment";
                if (kvp.Value > 1) si += "y";
                si += " " + kvp.Key.Name + " (" + kvp.Key.NumberOfPeople + " osobowy)";
                sb.AppendFormat("<a style=\"text-decoration:none;color:#666;\" href=\"{0}\">{1}</a><br />", UrlUtils.GetApartmentTypeUrl(kvp.Key, DisplayApartmentTypeView.Default, 1), si);
            }

            List<MailReservationLine> lines = new List<MailReservationLine>();
            MailReservationLine lineApartments = new MailReservationLine();
            lineApartments.Position = sb.ToString();
            lineApartments.PriceAll = new Currencies.Currency(reservation.FinalPrice, "PLN", 2).ToCurrency(reservation.Client.PrefferCurrency).ToString();
            lineApartments.PriceAllWithoutRabat = new Currencies.Currency(reservation.Price, "PLN", 2).ToCurrency(reservation.Client.PrefferCurrency).ToString();
            int lengthOfStay = (int)Math.Ceiling((reservation.DepartureDate - reservation.ArrivalDate).TotalDays);
            lineApartments.PriceNight = new Currencies.Currency(reservation.FinalPrice / lengthOfStay, "PLN", 2).ToCurrency(reservation.Client.PrefferCurrency).ToString() + " (za noc)";
            lineApartments.Rabat = reservation.Rabat + "%";
            lines.Add(lineApartments);

            ReservationAdditionalServicesOrder servicesOrder = GetReservationAdditionalServicesOrder(reservation);
            foreach (ReservationAdditionalService orderLine in servicesOrder.GetOrderingReservationServices()) {
                MailReservationLine line = new MailReservationLine();
                if (orderLine.Quantity > 1)
                    line.Position = string.Format("{0} * {1}", orderLine.Quantity, orderLine.Service.ServiceName);
                else
                    line.Position = orderLine.Service.ServiceName;
                line.PriceNight = new Currencies.Currency(orderLine.Price / orderLine.Quantity, "PLN", 2).ToCurrency(reservation.Client.PrefferCurrency).ToString();
                line.PriceAll = new Currencies.Currency(orderLine.Price, "PLN", 2).ToCurrency(reservation.Client.PrefferCurrency).ToString();
                line.PriceAllWithoutRabat = line.PriceAll;
                lines.Add(line);
            }

            repeater.DataSource = lines;
            repeater.DataBind();
        }

        public static string GetOverallPriceWithoutRabat(IWebReservation reservation) {
            ReservationAdditionalServicesOrder servicesOrder = GetReservationAdditionalServicesOrder(reservation);
            return new Currencies.Currency(reservation.Price + servicesOrder.Value, "PLN", 2).ToCurrency(reservation.Client.PrefferCurrency).ToString();
        }

        public static string GetOverallPrice(IWebReservation reservation) {
            ReservationAdditionalServicesOrder servicesOrder = GetReservationAdditionalServicesOrder(reservation);
            return new Currencies.Currency(reservation.FinalPrice + servicesOrder.Value, "PLN", 2).ToCurrency(reservation.Client.PrefferCurrency).ToString();
        }

        private static ReservationAdditionalServicesOrder GetReservationAdditionalServicesOrder(IWebReservation reservation) {
            ReservationAdditionalServicesOrder order = null;
            if (HttpContext.Current != null) {
                Page page = HttpContext.Current.Handler as Page;
                if (page != null && page.Items.Contains("ReservationAdditionalServicesOrder-" + reservation.ReservationId)) {
                    order = page.Items["ReservationAdditionalServicesOrder-" + reservation.ReservationId] as ReservationAdditionalServicesOrder;
                }
            }
            if (order == null) {
                order = new ReservationAdditionalServicesOrder(reservation);
                if (HttpContext.Current != null) {
                    Page page = HttpContext.Current.Handler as Page;
                    if (page != null)
                        page.Items.Add("ReservationAdditionalServicesOrder-" + reservation.ReservationId, order);
                }
            }
            return order;
        }

        public static void PopulateDynamicReservationAparts(List<IReservation> reservationItems, Repeater repeater) {
            repeater.DataSource = reservationItems;
            repeater.DataBind();
            return;
            Dictionary<IApartment, int> d = new Dictionary<IApartment, int>();
            Dictionary<IApartment, double> dp = new Dictionary<IApartment, double>();
            foreach (IReservation r in reservationItems) {
                if (!d.ContainsKey(r.Apartment)) {
                    d.Add(r.Apartment, 0);
                    dp.Add(r.Apartment, 0);
                }
                d[r.Apartment]++;
                dp[r.Apartment] += r.Price.GetPrice();
            }

            List<string> s = new List<string>();
            foreach (KeyValuePair<IApartment, int> kvp in d) {
                string si = kvp.Value + " apartment";
                if (kvp.Value > 1) si += "y";
                si += " " + kvp.Key.Group.Name + " (" + kvp.Key.NumberOfPeople + " osobowy)";
                s.Add(si);
            }
            repeater.DataSource = s;
            repeater.DataBind();
        }

        public static string MakeUrl(string relativeUrl) {
            return MakeUrl(relativeUrl, true);
        }

        public static string MakeUrl(string relativeUrl, bool makeAbsolute) {
            relativeUrl = UrlUtils.LocalizeUrl(Factory.Instance().GetPreFolderEvaluation(), relativeUrl);
            if (makeAbsolute) {
                relativeUrl = ConfigurationManager.AppSettings["Domain"] + relativeUrl;
                if (!relativeUrl.StartsWith("http"))
                    relativeUrl = "http://" + relativeUrl;
            }
            else {
                if (!relativeUrl.StartsWith("/"))
                    relativeUrl = "/" + relativeUrl;
            }
            return relativeUrl;
        }

        public static string FormatDateRange(DateTime dt1, DateTime dt2) {

            string s = "";

            if (dt1.Date.Equals(dt2.Date))
                s = dt1.ToString("d MMMM yyyy");
            else {
                s = dt1.ToString(GetFormatStartDate(dt1, dt2));
                s += (" - " + dt2.ToString("d MMMM yyyy"));
            }
            return s;
        }

        private static string GetFormatStartDate(DateTime dt1, DateTime dt2) {
            if (dt1.Year != dt2.Year)
                return "d MMMM yyyy";
            else {
                string format = "d ";
                if (dt1.Month != dt2.Month)
                    format += "MMMM";
                return format;
            }

        }

        public static float GetAbsoluteValueOfWebRabat() {
            IPriceRabat rabat = Factory.Instance().GetPriceRabat("web");
            if (rabat != null)
                return Math.Abs(rabat.RabatValue);
            else return 0;
        }

    }
}